package com.dw.monitor.cm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.cloudera.api.ApiRootResource;
import com.cloudera.api.ApiUtils;
import com.cloudera.api.ClouderaManagerClientBuilder;

import com.cloudera.api.model.ApiTimeSeriesRequest;
import com.cloudera.api.v11.RootResourceV11;

import com.cloudera.api.v11.TimeSeriesResourceV11;
import com.dw.monitor.tool.Utc;
import com.dw.monitor.tool.jdbc;
import com.dw.monitor.tool.testJdbc;


import javax.ws.rs.core.Response;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.dw.monitor.tool.Utc.getNow;
import static com.dw.monitor.tool.Utc.getUtc;



public class test {
    private static String cdhApiPath = "172.16.2.156";
    private static String cdhApiPort = "7180";
    private static String cdhApiUserName = "admin";
    private static String cdhApiPassword = "admin";
    public static JSONObject getTimeSeriesResponse(String query, String from, String to) throws ParseException {

        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date fromDate = dfs.parse(from);
        Date toDate = dfs.parse(to);
        String fromformat = ApiUtils.printDate(fromDate);
        String toformat = ApiUtils.printDate(toDate);

        long between = (toDate.getTime() - fromDate.getTime());
        int minutes = (int) (between / (1000 * 60));
        String desire = "RAW";
        if (minutes <= 1440) {
            desire = "RAW";

            //} else if (minutes > 30 && minutes < 300) {
            //    desire = "TEN_MINUTELY";
            //} else if (minutes >= 300 && minutes < 1800) {
            //    desire = "HOURLY";
            //} else if (minutes >= 1800 && minutes < 10800) {
            //    desire = "SIX_HOURLY";
        } else {
            desire = "DAILY";
        }

        System.out.println("desire" + desire);
        System.out.println("fromformat" + fromformat);
        System.out.println("toformat" + toformat);
        ApiTimeSeriesRequest atsr = new ApiTimeSeriesRequest();
        System.out.println(query);
        atsr.setQuery(query);
        atsr.setFrom(fromformat);
        atsr.setTo(toformat);
        atsr.setDesiredRollup(desire);
        atsr.setMustUseDesiredRollup(true);
        ApiRootResource root = new ClouderaManagerClientBuilder().withHost(cdhApiPath)
                .withPort(Integer.parseInt(cdhApiPort)).withUsernamePassword(cdhApiUserName, cdhApiPassword).build();
        RootResourceV11 v11 = root.getRootV11();
        TimeSeriesResourceV11 t11 = v11.getTimeSeriesResource();
        System.out.println();
        System.out.println(t11);
        System.out.println(atsr);
        Response res = t11.queryTimeSeries(atsr);
        String jsonResponse = res.readEntity(String.class);
        System.out.println("atsr"+atsr);
        System.out.println("res"+res);
        //System.out.println(jsonResponse);
        JSONObject jsonobj = JSON.parseObject(jsonResponse);

        //System.out.println(.toString());
        return jsonobj;
    }

    //获取json的数据
    public static void getJsonData1(JSONObject jsonobj, Connection conn,String entity_name,String type) throws ParseException, SQLException {
        //得到CDH中data里面的数据，是数组类型，然后遍历数据，拿到对应的数据
        System.out.println(jsonobj);
        JSONArray data = jsonobj.getJSONArray("items").getJSONObject(0)
                //.getJSONArray("data").getJSONObject(0)
                .getJSONArray("timeSeries").getJSONObject(0).getJSONArray("data");
        //判断数据是否为空
        if(data.size()>0){
            for(int i = 0 ;i < data.size();i++){
                JSONObject json = data.getJSONObject(i);
                String timestamp = getUtc(json.get("timestamp").toString());
                PreparedStatement psql = conn.prepareStatement("replace into dashboard_monitor_cdh_data (cluster_name,entity_name,type,date_f,time_stamp,value)" + "values(?,?,?,?,?,?)");
                psql.setString(1,"CLUSTER1");
                psql.setString(2,entity_name);
                psql.setString(3,type);
                psql.setString(4,timestamp.substring(0,10));
                psql.setString(5,timestamp);
                psql.setDouble(6,Double.valueOf(json.get("value").toString()));
                psql.executeUpdate();
                psql.close();
                //System.out.println("type:"+json.get("type")+",value:"+json.get("value")+",timestamp:"+timestamp);
            }
        }
    }

    public static void main(String[] args) {
        String query1 = "SELECT total_bytes_read_rate_across_datanodes WHERE entityName = \"hdfs\" AND category = SERVICE";
        String query2 = "SELECT total_bytes_written_rate_across_datanodes WHERE entityName = \"hdfs\" AND category = SERVICE";
        String query3 = "SELECT total_bytes_receive_rate_across_network_interfaces WHERE entityName = \"1\" AND category = CLUSTER";
        String query4 = "SELECT total_bytes_transmit_rate_across_network_interfaces WHERE entityName = \"1\" AND category = CLUSTER";
        String query5 = "SELECT total_read_bytes_rate_across_disks WHERE entityName = \"1\" AND category = CLUSTER";
        String query6 = "SELECT total_write_bytes_rate_across_disks WHERE entityName = \"1\" AND category = CLUSTER";
        String query7 = "SELECT cpu_percent_across_hosts WHERE entityName = \"1\" AND category = CLUSTER";
        String query8 = "SELECT allocated_memory_mb_cumulative WHERE entityName = \"yarn:root\" AND category = YARN_POOL";
        String query9 = "SELECT allocated_vcores_cumulative WHERE entityName = \"yarn:root\" AND category = YARN_POOL";
        String query10 = "SELECT available_memory_mb WHERE entityName = \"yarn:root\" AND category = YARN_POOL";
        String query11 = "SELECT available_vcores WHERE entityName = \"yarn:root\" AND category = YARN_POOL";
        String query12 = "SELECT dfs_capacity WHERE entityName = \"hdfs:ns1\" AND category = SERVICE";
        String query13 = "SELECT dfs_capacity_used WHERE entityName = \"hdfs:ns1\" AND category = SERVICE";
        String query14 = "SELECT dfs_capacity_used_non_hdfs WHERE entityName = \"hdfs:ns1\" AND category = SERVICE";
        String from = Utc.timeStampToDate(String.valueOf(System.currentTimeMillis()-1000*60*60*2));
        System.out.println(query1);
        System.out.println(from);
        String end = Utc.getNowDetail();
        System.out.println(end);
        Connection conn = testJdbc.getConn();
        try {
            JSONObject json1 = getTimeSeriesResponse(query1, from, end);
            System.out.println(1);
            JSONObject json2 = getTimeSeriesResponse(query2, from, end);
            System.out.println(2);
            JSONObject json3 = getTimeSeriesResponse(query3, from, end);
            System.out.println(3);
            JSONObject json4 = getTimeSeriesResponse(query4, from, end);
            System.out.println(4);
            JSONObject json5 = getTimeSeriesResponse(query5, from, end);
            System.out.println(5);
            JSONObject json6 = getTimeSeriesResponse(query6, from, end);
            System.out.println(6);
            JSONObject json7 = getTimeSeriesResponse(query7, from, end);
            System.out.println(7);
            JSONObject json8 = getTimeSeriesResponse(query8, from, end);
            System.out.println(8);
            JSONObject json9 = getTimeSeriesResponse(query9, from, end);
            JSONObject json10 = getTimeSeriesResponse(query10, from, end);
            JSONObject json11 = getTimeSeriesResponse(query11, from, end);
            JSONObject json12 = getTimeSeriesResponse(query12, from, end);
            JSONObject json13 = getTimeSeriesResponse(query13, from, end);
            JSONObject json14 = getTimeSeriesResponse(query14, from, end);
            test.getJsonData1(json1,conn,"HDFS","READ");
            test.getJsonData1(json2,conn,"HDFS","WRITTEN");
            test.getJsonData1(json3,conn,"NETWORK","RECEIVE");
            test.getJsonData1(json4,conn,"NETWORK","TRANSMIT");
            test.getJsonData1(json5,conn,"DISK","READ");
            test.getJsonData1(json6,conn,"DISK","WRITTEN");
            test.getJsonData1(json7,conn,"CPU","USED");
            test.getJsonData1(json8,conn,"MEMORY","ALLOCATED");
            test.getJsonData1(json9,conn,"VCORES","ALLOCATED");
            test.getJsonData1(json10,conn,"MEMORY","AVAILABLE");
            test.getJsonData1(json11,conn,"VCORES","AVAILABLE");
            test.getJsonData1(json12,conn,"DFS","CAPACITY");
            test.getJsonData1(json13,conn,"DFS","CAPACITY_Y");
            test.getJsonData1(json14,conn,"DFS","CAPACITY_N");
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //String items = ;
        //System.out.println(items);
    }
}
